package han.chensing.latos.game.util;

import com.badlogic.gdx.files.FileHandle;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerUtil {
    public static byte[] toBytes(Object object)
            throws Exception{
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        objectOutputStream.close();
        byteArrayOutputStream.close();
        return bytes;
    }

    @SuppressWarnings({"unused", "unchecked"})
    public static <T> T toObject(InputStream inputStream, Class<T> tClass)
        throws Exception{
        ObjectInputStream objectInputStream=new ObjectInputStream(inputStream);
        T t = (T) objectInputStream.readObject();
        objectInputStream.close();
        return t;
    }

    @SuppressWarnings({"unused", "unchecked"})
    public static <T> T toObject(FileHandle fileHandle, Class<T> tClass)
            throws Exception{
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(fileHandle.readBytes());
        ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);
        T t = (T) objectInputStream.readObject();
        objectInputStream.close();
        return t;
    }

}
